const models = require("../db/mysqldb/index");
const { Op } = require("sequelize");
const { getDescendants } = require("../utils/utils");

class DataSystemDeptModel {
  /**
   * @description 通过 dept_id 查找数据，不包含删除数据
   * @param {string} dept_id
   * @returns
   */
  static async findBySystemDeptId({ dept_id }) {
    return await models.sys_dept.findOne({
      where: {
        dept_id,
      },
    });
  }
  /**
   * @description 通过 dept_id 查找数据，不包含删除数据
   * @param {string} dept_id
   * @returns
   */
  static async findExcludeBySystemDeptId({ dept_id }) {
    try {
      let allData = await models.sys_dept.findAll({
        where: {
          del_flag: "0",
        },
      });
      let data = [];
      if (allData.length) {
        const currentDeptIds = getDescendants(allData, dept_id);
        let ids = currentDeptIds.map(item=>{
          return item.dept_id
        })
        data = allData
          .filter((item) => !ids.includes(item.dept_id))
          .filter((item) => item.dept_id !== dept_id);
        return { data, error: null };
      }
    } catch (error) {
      return { data: [], error };
    }
  }
  /**
   * @description create
   * @param {Number} parent_id
   * @param {String} dept_name
   * @param {Number} order_num
   * @param {String} leader
   * @param {String} phone
   * @param {String} email
   * @param {Number} status
   * @param {String} remark
   * @param {String} op_user_id
   * @returns
   */
  static async create({
    dept_name,
    parent_id,
    order_num,
    leader,
    phone,
    email,
    status,
    remark,
    op_user_id,
  }) {
    return await models.sys_dept.create({
      parent_id,
      dept_name,
      order_num,
      leader,
      phone,
      email,
      status,
      remark,
      create_by: op_user_id,
      create_time: Date.now(),
    });
  }
  /**
   * @description 更新
   * @param {Number} parent_id
   * @param {String} dept_name
   * @param {Number} order_num
   * @param {String} leader
   * @param {String} phone
   * @param {String} email
   * @param {Number} status
   * @param {String} remark
   * @param {String} op_user_id
   * @param {Number} dept_id
   * @returns
   */
  static async update({
    parent_id,
    dept_name,
    order_num,
    leader,
    phone,
    email,
    status,
    remark,
    op_user_id,
    dept_id,
  }) {
    return await models.sys_dept.update(
      {
        parent_id,
        dept_name,
        order_num,
        leader,
        phone,
        email,
        status,
        remark,
        update_by: op_user_id,
        update_time: Date.now(),
      },
      {
        where: { dept_id },
      }
    );
  }
  /**
   * @description 删除
   * @param {*} op_user_id
   * @param {*} dept_id
   * @returns
   */
  static async delete({ op_user_id, dept_id }) {
    return await models.sys_dept.update(
      {
        del_flag: "2",
        update_by: op_user_id,
      },
      {
        where: { dept_id },
      }
    );
  }

  /**
   * @description 批量删除
   * @param {Number} op_user_id
   * @param {Array} ids
   * @returns
   */
  static async deleteByIds({ op_user_id, ids }) {
    return await models.sys_dept.update(
      {
        del_flag: "2",
        update_by: op_user_id,
      },
      {
        where: {
          dept_id: {
            [Op.in]: ids,
          },
        },
      }
    );
  }

  /**
   * @description 当前用户的部门信息
   * @param {*} user_id
   * @returns
   */
  static async findDeptByUserID({ user_id }) {
    let sql = `select sd.dept_id,sd.parent_id,sd.dept_name,sd.order_num,sd.leader,sd.phone,sd.email,sd.status
     from sys_user su LEFT JOIN sys_dept sd on su.dept_id = sd.dept_id where su.user_id = ${user_id} and sd.del_flag = '0'`;
    return await models.sequelize.query(sql, {
      replacements: ["active"],
      type: models.sequelize.QueryTypes.SELECT,
    });
  }
  /**
   * @description 获取所有岗位信息
   * @returns
   */
  static async list ({ data_scope, dept_name, status }) {
    let querySql = '';
    if (dept_name) {
      querySql += ` and dept_name like '%${dept_name}%'`
    }
    if (status) {
      querySql += ` and status = ${status}`
    }
    let sql = `SELECT
        parent_id,
        dept_name,
        dept_id,
        dept_name,
        order_num,
        leader,
        phone,
        email,
        status,
        remark,
        update_time,
        create_by,
        create_time,
        update_by
      FROM
        sys_dept WHERE del_flag = '0' ${querySql}
      ORDER BY
        order_num ASC,
        create_time DESC,
        update_time DESC`;
    return await models.sequelize.query(sql, {
      replacements: ["active"],
      type: models.sequelize.QueryTypes.SELECT,
    });
  }
  /**
   * @description 获取所有岗位信息
   * @returns
   */
  static async all({ data_scope }) {
    let sql = `SELECT
        parent_id,
        dept_name as label,
        dept_id as id
      FROM
        sys_dept WHERE del_flag = '0' ${data_scope}
      ORDER BY
        order_num ASC,
        create_time DESC,
        update_time DESC`;
    return await models.sequelize.query(sql, {
      replacements: ["active"],
      type: models.sequelize.QueryTypes.SELECT,
    });
  }
  static async findBySystemRoleId ({ role_id }) {
    let sql = `
    SELECT srm.dept_id
    from sys_role_dept srm left join sys_dept sm on srm.dept_id = sm.dept_id
    WHERE srm.role_id = ${role_id}
      and sm.status = '1' `;
    return await models.sequelize.query(sql, {
      replacements: ["active"],
      type: models.sequelize.QueryTypes.SELECT,
    });
  }
}
module.exports = {
  DataSystemDeptModel,
};
